<template>
	<div>
		<div class="header block">
			<div class="row">
				<div class="search">
					<input type="text" placeholder="请输入单位名称" class="input search-input" v-model="searchText"
						@keydown.enter="search" />
					<button class="btn" @click="search">搜索</button>
					<button class="btn-white" @click="onReset">重置</button>
				</div>
				<div>
					<button class="btn" style="width:128px" @click="onShowAddCompany">添加被派遣单位</button>
				</div>
			</div>
		</div>
		<div class="container block block-alone">
			<el-tabs model-value="detail">
				<div class="table">
					<el-table :data="tableData" style="width: 100%" :header-row-style="{ color: '#202536' }"
						:row-style="{ color: '#5E617D' }" @selection-change="handleSelectionChange">
						<!-- <el-table-column type="index" label="序号" /> -->
						<el-table-column prop="serveCompanyName" label="被派遣单位" width="200px">
							<template #header>
								<div class="flex flex-ai-c">
									<div>被派遣单位</div>

									<el-tooltip class="box-item" effect="dark" content="派遣单位状态，仅代表当前派遣单位是否可以投保"
										placement="top-start">
										<el-icon>
											<Warning />
										</el-icon>
									</el-tooltip>
								</div>
							</template>
							<template #default="scope">
								<div class="flex">
									<div class="status-box">
										<div class="status" :class="[`status-${scope.row.status}`]">{{ statusMap[scope.row.status] }}</div>
									</div>
									<div>{{ scope.row.serveCompanyName }}</div>
								</div>
							</template>
						</el-table-column>
						<el-table-column width="200px" label="已审核通过的工种">
							<template #default="scope">
								<p v-for="(item, index) in scope.row.occupationList" v-bind:key="index">
									{{ item.name }} {{ '(' + item.level + '类' + ')' }}
								</p>
							</template>
						</el-table-column>
						<!-- <el-table-column label="视频">
              <template #default="scope">
                <p
                  style="color:#1989FA"
                  class="point"
                >
                  <a v-if="scope.row.fileDetail" class="left-video-a" style="color:#1989FA;text-decoration:none;"
                     target="_blank" :href="scope.row.fileDetail">点击查看</a>
                  {{ !scope.row.fileDetail ? '暂无视频' : '' }}
                </p>
              </template>
            </el-table-column> -->
						<el-table-column width="110px" label="最新申请视频">
							<template #default="scope">
								<div v-if="isFirstApply(scope.row)">
									<p v-if="scope.row?.fileDetailList?.length"
										style="color:#1989FA" class="point"
										@click="onFileDetail(scope.row.fileDetailList)">点击查看</p>
									<p v-else>暂无视频</p>
								</div>
								<div v-else>
									<p v-if="scope.row.occupationRecord?.fileDetails?.length"
										style="color:#1989FA" class="point"
										@click="onFileDetail(mapUrl(scope.row.fileDetailList))">点击查看</p>
									<p v-else>暂无视频</p>
								</div>

								<!-- <div>
									<p v-if="scope.row.fileDetailList && scope.row.fileDetailList[0] !== ''"
										style="color:#1989FA" class="point"
										@click="onFileDetail(scope.row.fileDetailList)">点击查看</p>
									<p class="">{{ scope.row.fileDetailList && scope.row.fileDetailList[0] === '' ?
						'暂无视频' : '' }}</p>
								</div> -->

							</template>
						</el-table-column>
						<el-table-column width="200px" prop="createTime" label="最新申请时间">
							<template #default="scope">
								<div v-if="isFirstApply(scope.row)">
									{{scope.row.createTime}}
								</div>
								<div v-else>
									{{scope.row.occupationRecord?.createTime || '--'}}
								</div>
							</template>
						</el-table-column>
						<el-table-column width="120px" label="最新申请状态">
							<template #header>
								<div class="flex flex-ai-c">
									<div>最新申请状态</div>
									<el-tooltip class="box-item" effect="dark" content="最新上传视频的申请状态"
										placement="top-start">
										<el-icon>
											<Warning />
										</el-icon>
									</el-tooltip>
								</div>
							</template>
							<template #default="scope">
								<div class="decorate-box">
									<div v-if="isFirstApply(scope.row)" class="decorate" :class="[`decorate-${ scope.row.status}`]">
									</div>
									<div v-else class="decorate" :class="[`decorate-${scope.row.occupationRecord?.status}`]">
									</div>
									<p v-if="isFirstApply(scope.row)" >
										{{statusMap[scope.row.status]}}
									</p>
									<p v-else>
										{{statusMap[scope.row.occupationRecord?.status]}}
									</p>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="特别约定" prop="remark">
						</el-table-column>
						<el-table-column label="驳回理由" prop="rejectRemark"></el-table-column>
						<el-table-column width="170px" label="操作" fixed="right">
							<template #default="scope">
								<div class="flex gap-10">
									<!-- <p v-if="scope.row.status !== 3 && (scope.row.status || scope.row.status===0)" style="color:#FF7E68"
										class="point" @click="
						deleteDispatchExamine(scope.row.id)
						">
										删除
									</p> -->
									<p v-if="scope.row.status===1 && (!scope.row.occupationRecord || scope.row.occupationRecord?.status===1)" style="color:#FF7E68"
										class="point" @click="
						deleteDispatchExamine(scope.row.id)
						">
										删除
									</p>
									<p v-if="!scope.row.status" class="point fc-blue" @click="
						cancelDispatchExamine(scope.row.id)
						">
										撤销
									</p>
									<!-- 撤销新工种 -->
									<p v-if="scope.row.status === 1 && scope.row.occupationRecord?.status===0" class="point fc-blue" @click="
						onWithDrawOccupation(scope.row.occupationRecord.id)
						">
										撤销
									</p>

									<p class="point fc-blue" @click="onShowDetailDrawer(scope.row)">
										详情
									</p>
									<!-- 申请新工种 -->
									<p v-if="scope.row.status === 1 && scope.row.occupationRecord?.status !== 0" class="point fc-blue" @click="onApplyNewOccupation(scope.row.serveCompanyId, scope.row.id)">
										申请
									</p>
									<!-- <p v-if="scope.row.status === 2" class="point fc-blue" @click="onApplyNewOccupation(scope.row.serveCompanyId)">
										重新上传
									</p> -->
								</div>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination class="pagination" v-model:currentPage="pageNum" v-model:page-size="pageSize"
						:page-sizes="[10, 30, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
						@size-change="handleSizeChange" @current-change="getPayrollList">
					</el-pagination>
				</div>
			</el-tabs>
			<batchPayroll v-if="isBatchPay" @close="isBatchPay = false" @complete="getPayrollList" isType="payroll" />
		</div>
		<!-- <el-dialog v-model="centerDialogVisible" title="新增被派遣单位" width="642px" destroy-on-close center>
			<div class="row">
				<div class="name">
					<span class="important" style="opacity: -0.9">*</span>
					上传视频
				</div>
				<div class="upload-box" style="width:100%">
					<el-upload class="upload-demo" :action="uploadAction" :headers="{ Authorization }"
						:on-success="fileSuccess" :on-error="fileEerror" :show-file-list='false'
						:before-upload="fileBeforeUpload" accept="image/jpeg,image/image/png,video/*">
						<button class="btn-white-blue" style="width:130px;background:#1989FA;color:#fff;">
							<i class="el-icon el-icon-camera" />选择视频文件
						</button>
					</el-upload>
					<div class="upload-introduce">
						视频时间10s-60s 视频大小不超50M
					</div>
				</div>
			</div>
			<div class="row">
				<div class="name">
					<span class="important">*</span>
					被派遣单位
				</div>
				<div style="width:100%">
					<el-select v-model="companyId" filterable placeholder="请选择派遣单位">
						<el-option v-for="item in companyList" :key="item.id" :label="item.serveCompanyName"
							:value="item.id" />
					</el-select>
				</div>
			</div>
			<div class="dialog-btn-box">
				<button class="btn-white" @click="centerDialogVisible = false" style="marginRight:20px">取消</button>
				<button class="btn" @click="addDispatchUnit" style="marginLength:20px">提交审核</button>
			</div>
		</el-dialog> -->
		<!--  -->
		<alertBox :data-title="(videoIndex + 1) + '/' + videoList.length" v-if="videoList.length" :isCloseType="true"
			@close="onVideoCallback">
			<div class="alert-box">
				<div class="video-box">
					<div> <i style="font-size:50px" class="el-icon el-icon-arrow-left" @click="onVideoUpper" /> </div>
					<div class="video-list">
						<div v-for="(item, index) in videoList" v-bind:key="index">
							<!-- video -->
							<!-- height="500"  -->
							<video class="video" :src="item" preload controls v-if="videoIndex === index"></video>
						</div>
					</div>
					<div><i style="font-size:50px" class="el-icon el-icon-arrow-right" @click="onVideoNext" /> </div>
				</div>
			</div>
		</alertBox>
	</div>
	<LongInsureDispatchDrawer v-model:show="showDetail" :id="itemDetail.id" @success="getPayrollList" />
	<DialogAddCompany v-model:show="showAddCompany" :cur-company-id="curCompanyId" :id="curId" :add-type="addType"
		@success="getPayrollList" />
</template>

<script lang="ts">
import global from '@/utils/global'
import { defineComponent } from 'vue'
import { ElMessageBox } from 'element-plus'
import {
	getDispatchList,
	cancelDispatchExamine,
	deleteDispatchExamine,
	addDispatch,
	getCompanyList,
	deleteOccupation
} from '@/api/long-insure'
import { BillDetailDto, BillDto } from '@/api/bill'
import { getPayrollList } from '@/api/payroll'
import batchPayroll from '@/components/batch-payroll.vue'
import alertBox from '@/components/alert-box.vue'
import uploadVideo from '@/components/upload-video/index.vue'
import LongInsureDispatchDrawer from './components/drawer/LongInsureDispatchDrawer.vue'
import DialogAddCompany from './components/long-insure-dispatch/DialogAddCompany.vue'
export default defineComponent({
	name: 'LongInsureDispatch',
	components: {
		batchPayroll,
		alertBox,
		uploadVideo,
		LongInsureDispatchDrawer,
		DialogAddCompany
	},
	data() {
		return {
			Authorization: 'Bearer' + ' ' + global.token,
			uploadAction:
				process.env.VUE_APP_BASE_URL +
				'/rest/period-insur/serve-company/upload', // 上传路径
			isBatchPay: false,
			pageSize: 10,
			pageNum: 1,
			total: 0,
			tableData: [] as BillDetailDto[],
			searchText: '',
			searchValue: '',
			detailInfo: {} as BillDto,
			selects: [] as string[],
			centerDialogVisible: false, // 弹窗
			fileSize: '',
			fileUrl: '',
			fileList: [] as any,
			isfileLengt: true,
			dispatchUnit: '', // 派遣单位
			companyList: [] as any, // 所有单位
			companyId: '', // 选择的单位id
			videoList: [] as string[],
			videoIndex: 0,
			showDetail: false,
			itemDetail: {},
			showAddCompany: false,
			curCompanyId: 0,
			curId: 0,
			addType: 'add', // 'add' 添加被派遣单位 'apply' 申请新工种
			statusMap: {
				0: '待审核',
				1: '已通过',
				2: '已驳回',
				3: '已禁用'
			}
		}
	},
	computed: {
		mapUrl() {
			return (list: any) => {
				if (list?.length) {
					return list.map((i: any) => i.fileUrl || i)
				}
				return []
			}
		},
		isFirstApply() {
			return (data: any) => {
				return data.status === 0 || (data.status === 1 && !data.occupationRecord) || data.status === 2
			}
		}
	},
	created() {
		this.getPayrollList()
		this.getCompanyList()
	},
	methods: {
		// 获取所有单位列表
		async getCompanyList() {
			const result = await getCompanyList()
			console.log(result, 'result获取所有单位列表')
			this.companyList = result.list
		},
		// 取消 派遣段位 审核
		async cancelDispatchExamine(id: string) {
			ElMessageBox.confirm(
				'确定撤销该条记录？',
				'撤销确认',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
				.then(async () => {
					const result = await cancelDispatchExamine({ id: id })
					await this.getPayrollList()
					this.$message.success('撤销成功！')
				})
		},
		// 删除派遣单位
		async deleteDispatchExamine(id: string) {
			console.log(id, 'id')
			ElMessageBox.confirm(
				'删除后该企业将无法投保，已申请是工种将被清除，确定删除？',
				'删除投保企业确认',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
				.then(async () => {
					const result = await deleteDispatchExamine({ id: id })
					await this.getPayrollList()
					this.$message.success('删除成功！')
				})
		},
		async getPayrollList() {
			const result = await getDispatchList({
				pageSize: this.pageSize,
				pageNum: this.pageNum,
				isGetFile: 1,
				searchText: this.searchValue
			})
			this.total = result.total
			this.tableData = result.list
		},
		handleSizeChange() {
			this.pageNum = 1
			this.getPayrollList()
		},
		search() {
			this.searchValue = this.searchText
			this.pageNum = 1
			this.getPayrollList()
		},
		onReset() {
			this.searchText = ''
			this.search()
		},
		handleSelectionChange(selects: { id: string }[]) {
			this.selects = selects.map(item => item.id)
		},
		// async fileBeforeUpload(file: any) {
		// 	var url = URL.createObjectURL(file)
		// 	var audioElement = new Audio(url)
		// 	var duration = parseInt(audioElement.duration + '')
		// 	audioElement.addEventListener('loadedmetadata', () => {
		// 		console.log(parseInt(audioElement.duration + ''), '时长为秒，取整')// 时长为秒，取整
		// 		const fileLength = parseInt(audioElement.duration + '')
		// 		if (fileLength < 10 && fileLength > 60) {
		// 			this.$message.error('视频不可小于10秒或大于60秒')
		// 			this.isfileLengt = false
		// 			return
		// 		}
		// 		if ((file.size / 1024 / 1024) > 50) {
		// 			this.$message.error('视频不可大于50M')
		// 			this.isfileLengt = false
		// 		}
		// 	})
		// },
		// fileSuccess(response: { code: number, msg: string, data: { fileSize: string, fileUrl: string } }, file: { raw: { name: string, type: string } }) {
		// 	console.log(file.raw, 'file.raw')
		// 	if (response.code === 500) {
		// 		this.$message.error(response.msg)
		// 		return
		// 	}
		// 	if (file.raw.type !== 'video/mp4') {
		// 		this.$message.error('请上传视频')
		// 		return
		// 	}
		// 	// if (!this.isfileLengt) {
		// 	//     this.$message.error('视频不可小于10秒或大于100秒')
		// 	//     return
		// 	// }
		// 	this.fileSize = response.data.fileSize
		// 	this.fileUrl = response.data.fileUrl
		// 	console.log(file, 'file', file.raw.type)
		// 	this.$message.success('上传成功')
		// },
		// fileEerror() {
		// 	this.$message.error('文件上传失败')
		// },
		// 被派遣单位
		// async addDispatchUnit() {
		// 	console.log('添加派遣单位')
		// 	console.log(this.companyId, 'companyId')
		// 	// if (!this.fileList?.length) {
		// 	//     this.$message.error('请至少上传一个视频')
		// 	//     return
		// 	// }
		// 	if (!this.fileUrl) {
		// 		this.$message.error('请至少上传一个视频')
		// 		return
		// 	}
		// 	const result = await addDispatch({
		// 		serveCompanyId: Number(this.companyId),
		// 		params: {
		// 			// video: this.fileList[0].fileUrl
		// 			video: this.fileUrl
		// 		}
		// 	})
		// 	console.log(result, 'result')
		// 	this.centerDialogVisible = false
		// 	await this.getPayrollList()
		// 	this.$message.success('提交被派遣单位成功')
		// },
		// 获取派遣单位视频
		onFileDetail(fileList: string[]) {
			console.log(23331, fileList)
			this.videoList = fileList
			console.log(fileList, 'fileList')
			console.log('123456789')
		},
		// 关闭视频查看弹窗
		onVideoCallback() {
			this.videoList = []
			this.videoIndex = 0
		},
		// 查看上一个视频
		onVideoUpper() {
			// videoList: [] as string[],
			// videoIndex: 0
			if (this.videoIndex === 0) {
				return
			}
			this.videoIndex = this.videoIndex -= 1
		},
		// 查看下一个视频
		onVideoNext() {
			if (this.videoIndex === (this.videoList.length - 1)) {
				return
			}
			this.videoIndex = this.videoIndex += 1
		},
		/**
		 * 点击详情按钮
		 * @param id
		 */
		onShowDetailDrawer(item: any) {
			this.itemDetail = item
			this.showDetail = true
		},
		onShowAddCompany() {
			this.addType = 'add'
			this.showAddCompany = true
		},
		onApplyNewOccupation(companyId: number, id: any = '') {
			this.addType = 'apply'
			this.curCompanyId = companyId
			this.curId = id
			this.showAddCompany = true
		},
		/**
		 * 撤销工种
		 */
		onWithDrawOccupation(id: number) {
			ElMessageBox.confirm(
				'确定撤销该条记录？',
				'撤销确认',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
				.then(async () => {
					const result = await deleteOccupation(id)
					await this.getPayrollList()
					this.$message.success('撤销成功！')
				})
		}
	}
})
</script>

<style lang="stylus" scoped>
table()
.header.block {
  padding 20px
}

.basic
  margin-top 20px

.value
  margin-right 30px

.value.important
  color color-red
  font-style italic

:deep().el-tabs__header.is-top
  display inline-block
  margin-top -20px

:deep().el-tabs__nav-scroll
  padding-right 20px

.height-right
  float: right

.download-btn
  width: 126px !important;

.btn-red
  background: #FF7E68

.el-tabs__header
  margin: 0

.block-alone
  padding: 0 24px 0

.decorate-box
  display flex
  align-items center

.decorate
  width 6px
  height 6px
  border-radius 50%
  margin-right 5px
	&.decorate-0
		background #FFA814
	&.decorate-1
		background #0256FF
	&.decorate-2
		background #EA0000
	&.decorate-3
		background #202536

.row
  margin-top 32px

  .name
    width 150px
    font-size 16px
    font-weight 500

.upload-box
  display flex
  align-items flex-end

.upload-introduce
  margin-left 16px
  color #1989FA

.dialog-btn-box
  display flex
  align-items center
  justify-content center
  margin-top 40px
.video-box
	display flex
	align-items center
	justify-content space-between
	padding 60px
.video-i
	height 600px
	width 350px
.video
	height 600px
	width 350px
.status-box
	flex-shrink 0
.status
	padding 0 6px
	border-radius 3px
	font-size 11px
	flex-shrink 0
	margin-right 5px
.status-1
	color #0256FF
	background rgba(2, 86, 255, 0.3)
.status-0
	color #FFA814
	background rgba(255, 168, 20, 0.3)
.status-2
	color #EA0000
	background rgba(234, 0, 0, 0.3)
.status-3
	color rgba(32, 37, 54, 1)
	background rgba(32, 37, 54, 0.1)
.status-4
	color #202536
	background rgba(32, 37, 54, 0.3)
</style>
